package com.thyme.content.sentineltest;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author thyme
 * @ClassName MyUrlBlockHandler
 * @Description TODO
 * @Date 2019/11/25 20:01
 */
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException ex) throws IOException {
        ErrorMsg errorMsg = null;
        if (ex instanceof FlowException) {
            // 流控异常
             errorMsg = ErrorMsg.builder()
                    .status(100)
                    .msg("限流异常")
                    .build();

        }else if (ex instanceof DegradeException) {
            // 降级异常
            errorMsg = ErrorMsg.builder()
                    .status(101)
                    .msg("降级异常")
                    .build();

        }else if (ex instanceof ParamFlowException) {
            // 热点异常
            errorMsg = ErrorMsg.builder()
                    .status(102)
                    .msg("热点异常")
                    .build();

        }else if (ex instanceof SystemBlockException) {
            // 系统异常
            errorMsg = ErrorMsg.builder()
                    .status(103)
                    .msg("系统异常")
                    .build();

        }else if (ex instanceof AuthorityException) {
            // 授权异常
            errorMsg = ErrorMsg.builder()
                    .status(104)
                    .msg("授权异常")
                    .build();

        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        new ObjectMapper()
                .writeValue(
                        httpServletResponse.getWriter(),
                        errorMsg
                );
    }
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ErrorMsg {
    private Integer status;
    private String msg;

}
